package control.networking;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

import view.ChatPanel;

/**
 * ChatClient is the back end to the ChatPanel in the user's
 * frame. Writes input from the user to the server, and appends
 * messages sent from other users to the chat box.
 * 
 * @author Kevin Luikens
 */
public class ChatClient extends Thread {
	
	private static final int PORT = 4000;			// server information
	private static final String HOST = "150.135.82.159";
		
	private File			file;		// file for chat log that will be output
	private Socket 			serverSock;	// connection to the client
	private BufferedReader 	in;			// Server ---> Client
	private PrintWriter 	out;		// Client ---> Server
	private ChatPanel		chatBox;
	
	/**
	 * Initializes a new ChatClient, connected to the ChatPanel.
	 * @param cb
	 */
	public ChatClient( ChatPanel cb ) {
		chatBox = cb;
		chatBox.setChatClient( this );
		
		try {
			serverSock = new Socket(HOST, PORT);
			in = new BufferedReader( new InputStreamReader( serverSock.getInputStream() ));
			out = new PrintWriter( serverSock.getOutputStream(), true );			
		} catch ( UnknownHostException e ) {
			e.printStackTrace();
		} catch ( IOException e ) {
			e.printStackTrace();	} 
	}

	/**
	 * The run method which will execute a when the Thread is started
	 * and wait for input to be sent to it.
	 */
	public void run() {
		String message;
		while(true) {
			try {
				message = in.readLine();
				processMessage( message );
			} catch (SocketException e) {
				break;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * Processes the message it receives, looking for keywords (commands) that
	 * can trigger special events.
	 * @param message 
	 */
	private void processMessage( String message ) {
		chatBox.appendText( message + "\n");
	}
	
	
	/**
	 * @param message Sends your message to the server, to broadcasted to other chatters.
	 */
	public void sendMessage( String message ) {
		out.println( message );
		System.out.println("sendMessage");
	}	
}
